{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Introduction\n",
    "\n",
    "In this notebook, we will explore the use of matrix representations of graphs, and show how their are direct matrix parallels for some of the algorithms that we have investigated."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import networkx as nx\n",
    "from networkx import bipartite\n",
    "import matplotlib.pyplot as plt\n",
    "import nxviz as nv\n",
    "from custom.load_data import load_university_social_network, load_amazon_reviews\n",
    "from matplotlib import animation\n",
    "from IPython.display import HTML\n",
    "import numpy as np\n",
    "\n",
    "%load_ext autoreload\n",
    "%autoreload 2\n",
    "%matplotlib inline\n",
    "%config InlineBackend.figure_format = 'retina'"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "For this notebook, we will specifically see the connection between matrix operations and pathfinding between nodes."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Toy Example: Linear Chain\n",
    "\n",
    "To start, let us use a simple four-node network, in which nodes are joined in a chain. Convince yourself that this is is a linear chain by running the cell below."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "nodes = list(range(4))\n",
    "G1 = nx.Graph()\n",
    "\n",
    "G1.add_nodes_from(nodes)\n",
    "G1.add_edges_from(zip(nodes, nodes[1:]))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Graph Form\n",
    "\n",
    "When visualized as circles and lines, the graph looks like this:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "nx.draw(G1, with_labels=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Matrix Form\n",
    "\n",
    "When represented in matrix form, it looks like the plot below. (Explain row by columns = node by nodes.)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "nv.MatrixPlot(G1).draw()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Playing with the matrix form\n",
    "\n",
    "NetworkX provides a `to_numpy_array()` function that will return a numpy array of the graph. That is used behind-the-scenes in `nxviz` to generate the MatrixPlot."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "A1 = nx.to_numpy_array(G1, nodelist=sorted(G1.nodes()))\n",
    "A1"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "One neat result is that if we take the adjacency matrix, and matrix-matrix multiply it against itself (\"matrix power 2\"), we will get back a new matrix that has interesting properties."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "# One way of coding this up\n",
    "np.linalg.matrix_power(A1, 2)\n",
    "\n",
    "# Another equivalent way, that takes advantage of Python 3.5's matrix multiply operator\n",
    "A1 @ A1"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Firstly**, if we look at the off-diagonals of the new matrix, this corresponds to the number of paths of length 2 that exist between those two nodes."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "np.diag(A1 @ A1)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Here, one path of length 2 exists between node 0 and node 2, and one path of length 2 exists between node 1 and node 3.\n",
    "\n",
    "**Secondly**, you may notice that the diagonals look like the degree of the nodes. This is a unique property of the 2nd adjacency matrix power: for every node, there are $ d $ degree paths of length two to get back to that same node.\n",
    "\n",
    "Not convinced? To get from a node and back, that's a path length of 2! :-)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Let's see if the following statment is true: The $ k^{th} $ matrix power of the graph adjacency matrix indicates how many paths of length $ k $ exist between each pair of nodes."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "np.linalg.matrix_power(A1, 3)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Indeed, if we think about it, there is, by definition, no way sequence of graph traversals that will allow us to go back to a node within 3 steps. We will always end up at some neighboring node.\n",
    "\n",
    "In addition, to get to the neighboring node in 3 steps, there are two ways to go about it:\n",
    "\n",
    "- node -> neighbor -> node -> neighbor\n",
    "- node -> neighbor -> neighbor's neighbor -> neighbor\n",
    "\n",
    "Or for the case of this chain graph:\n",
    "\n",
    "- 0 -> 1 -> 0 -> 1\n",
    "- 0 -> 1 -> 2 -> 1"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Toy Example: Directed Linear Chain\n",
    "\n",
    "Let's see if the same properties hold for a directed graph."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "nodes"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "G2 = nx.DiGraph()\n",
    "G2.add_nodes_from(nodes)\n",
    "G2.add_edges_from(zip(nodes, nodes[1:]))\n",
    "nx.draw(G2, with_labels=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Recall that in a directed graph, the matrix representation is not guaranteed to be symmetric."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "A2 = nx.to_numpy_array(G2)\n",
    "A2"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Let's look at the 2nd matrix power: the number of paths of length 2 between any pair of nodes."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "np.linalg.matrix_power(A2, 2)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We see that there's only one path from node 0 to node 2 of length 2, and one path from node 1 to node 3. If you're not convinced of this, trace it for yourself!"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Exercise\n",
    "\n",
    "In this directed graph, how many paths are there from node 0 to node 3 of length 3? Compute the 3rd matrix power and verify your answer."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Enter your code here.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Real Data\n",
    "\n",
    "Now that we've looked at a toy example, let's play around with a real dataset!\n",
    "\n",
    "This dataset is a residence hall rating dataset. From the [source website](http://konect.cc/networks/moreno_oz):\n",
    "\n",
    "> This directed network contains friendship ratings between 217 residents living at a residence hall located on the Australian National University campus. A node represents a person and edges contain ratings of one friend to another.\n",
    "\n",
    "For the purposes of this exercise, we will treat the edges as if they were unweighted.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "G = load_university_social_network()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Exercise\n",
    "\n",
    "Use nxviz's MatrixPlot to draw the graph."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Enter your code below.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Exercise\n",
    "\n",
    "Using what you know from the previous material, find out how many connected component subgraphs there are in the subgraph.\n",
    "\n",
    "**Hint:** You may need to convert the graph to an undirected one first."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Enter your code below.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Exercise\n",
    "\n",
    "Since there is only one connected component subgraph, pick two nodes in the graph and see how many shortest paths there exist between those two nodes.\n",
    "\n",
    "**Hint:** You will first need to know what the shortest path length is between those two nodes."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Enter your code below to find shortest path between two nodes."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Find out the number of possible shortest nodes between those two nodes."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Message Passing\n",
    "\n",
    "Message passing on graphs is a fascinating topic to explore. It's a neat way to think about a wide variety of problems, including the spread of infectious disease agents, rumours, and more. As it turns out, there's a direct matrix interpretation of the message passing operation.\n",
    "\n",
    "To illustrate this more clearly, let's go back to the directed chain graph, `G2`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "nx.draw(G2, with_labels=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "If we have a message that begins at node 0, and it is only passed to its neighbors, then node 1 is the next one that possess the message. Node 1 then passes it to node 2, and so on, until it reaches node 3.\n",
    "\n",
    "There are two key ideas to introduce here. Firstly, there is the notion of the **\"wavefront\"** of message passing: at the first time step, node 0 is the wavefront, and as time progresses, node 1, 2 and 3 progressively become the wavefront.\n",
    "\n",
    "Secondly, as the message gets passed, the number of nodes that have seen the message progressively increases. \n",
    "\n",
    "Let's see how this gets implemented in matrix form."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Matrix Message Passing\n",
    "\n",
    "To represent the data, we start with a vertical array of messages of shape `(1, 4)`. Let's use the following conventions:\n",
    "\n",
    "- `1` indicates that a node currently has the message.\n",
    "- `0` indicates that a node currently does not have the message.\n",
    "\n",
    "Since the message starts at node 0, let's put a `1` in that cell of the array, and `0`s elsewhere."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "msg = np.array([1, 0, 0, 0]).reshape(1, 4)\n",
    "msg"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In order to simulate one round of message passing, we matrix multiply the message with the adjacency matrix."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "msg2 = msg @ A2\n",
    "msg2"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The interpretation now is that the message is currently at node 1.\n",
    "\n",
    "To simulate a second round, we take that result and matrix multiply it against the adjacency matrix again."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "msg3 = msg2 @ A2\n",
    "msg3"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The interpretation now is that the message is currently at node 2."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Exercise\n",
    "\n",
    "Let's make an animation of this. I have pre-written the animation functions for you; your task is to implement the message passing function `propagate()` to precompute at each time step the message status."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# fig, ax = plt.subplots()\n",
    "\n",
    "def propagate(G, msg, n_frames):\n",
    "    \"\"\"\n",
    "    Computes the node values based on propagation.\n",
    "    \n",
    "    Intended to be used before or when being passed into the \n",
    "    anim() function (defined below).\n",
    "    \n",
    "    :param G: A NetworkX Graph.\n",
    "    :param msg: The initial state of the message.\n",
    "    :returns: A list of 1/0 representing message status at \n",
    "        each node.\n",
    "    \"\"\"\n",
    "    # Initialize a list to store message states at each timestep.\n",
    "    \n",
    "    \n",
    "    # Set a variable `new_msg` to be the initial message state.\n",
    "    \n",
    "    \n",
    "    # Get the adjacency matrix of the graph G.\n",
    "    \n",
    "    \n",
    "    # Perform message passing at each time step\n",
    "    for i in range(n_frames):\n",
    "        \n",
    "        \n",
    "        \n",
    "    # Return the message states.\n",
    "    return msg_states"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The rest of the `matplotlib` animation functions are shown below."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def update_func(step, nodes, colors):\n",
    "    \"\"\"\n",
    "    The update function for each animation time step.\n",
    "    \n",
    "    :param step: Passed in from matplotlib's FuncAnimation. Must\n",
    "        be present in the function signature.\n",
    "    :param nodes: Returned from nx.draw_networkx_edges(). Is an\n",
    "        array of colors.\n",
    "    :param colors: A list of pre-computed colors.\n",
    "    \"\"\"\n",
    "    nodes.set_array(colors[step].ravel())\n",
    "    return nodes\n",
    "\n",
    "def anim(G, initial_state, n_frames=4):\n",
    "    colors = propagate(G, initial_state, n_frames)\n",
    "    fig = plt.figure()\n",
    "    pos = {i:(i, i) for i in range(len(G))}\n",
    "    adj = nx.to_numpy_array(G)\n",
    "    pos = nx.kamada_kawai_layout(G)\n",
    "    nodes = nx.draw_networkx_nodes(G, pos=pos, node_color=colors[0].ravel(), node_size=20)\n",
    "    ax = nx.draw_networkx_edges(G, pos)\n",
    "    return animation.FuncAnimation(fig, update_func, frames=range(n_frames), fargs=(nodes, colors))\n",
    "\n",
    "\n",
    "# Initialize the message\n",
    "msg = np.zeros(len(G2))\n",
    "msg[0] = 1\n",
    "\n",
    "# Animate the graph with message propagation.\n",
    "HTML(anim(G2, propagate(G2, msg)).to_html5_video())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Exercise\n",
    "\n",
    "Visualize how a rumour would spread in the university dorm network. You can initialize the message on any node of your choice."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "msg = ____________\n",
    "msg[____] = _____\n",
    "HTML(anim(G, propagate(G, msg), n_frames=5).to_html5_video())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Bipartite Graph Matrices\n",
    "\n",
    "The section on message passing above assumed unipartite graphs, or at least graphs for which messages can be meaningfully passed between nodes. \n",
    "\n",
    "In this section, we will look at bipartite graphs. \n",
    "\n",
    "Recall from before the definition of a bipartite graph:\n",
    "\n",
    "- Nodes are separated into two partitions (hence 'bi'-'partite').\n",
    "- Edges can only occur between nodes of different partitions.\n",
    "\n",
    "Bipartite graphs have a natural matrix representation, known as the **biadjacency matrix**. Nodes on one partition are the rows, and nodes on the other partition are the columns.\n",
    "\n",
    "NetworkX's `bipartite` module provides a function for computing the biadjacency matrix of a bipartite graph."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Let's start by looking at a toy bipartite graph, a \"customer-product\" purchase record graph, with 4 products and 3 customers. The matrix representation might be as follows:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "# Rows = customers, columns = products, 1 = customer purchased product, 0 = customer did not purchase product.\n",
    "cp_mat = np.array([[0, 1, 0, 0],\n",
    "                   [1, 0, 1, 0],\n",
    "                   [1, 1, 1, 1]])\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "From this \"bi-adjacency\" matrix, one can compute the projection onto the customers, matrix multiplying the matrix with its transpose."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "c_mat = cp_mat @ cp_mat.T  # c_mat means \"customer matrix\"\n",
    "c_mat"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Pause here and read carefully!**\n",
    "\n",
    "What we get is the connectivity matrix of the customers, based on shared purchases. The diagonals are the degree of the customers in the original graph, i.e. the number of purchases they originally made, and the off-diagonals are the connectivity matrix, based on shared products."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "To get the products matrix, we make the transposed matrix the left side of the matrix multiplication."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "p_mat = cp_mat.T @ cp_mat  # p_mat means \"product matrix\"\n",
    "p_mat"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You may now try to convince yourself that the diagonals are the number of times a customer purchased that product, and the off-diagonals are the connectivity matrix of the products, weighted by how similar two customers are."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Exercises \n",
    "\n",
    "In the following exercises, you will now play with a customer-product graph from Amazon. This dataset was downloaded from [UCSD's Julian McAuley's website](http://jmcauley.ucsd.edu/data/amazon/), and corresponds to the digital music dataset.\n",
    "\n",
    "This is a bipartite graph. The two partitions are:\n",
    "\n",
    "- `customers`: The customers that were doing the reviews.\n",
    "- `products`: The music that was being reviewed.\n",
    "\n",
    "In the original dataset (see the original JSON in the `datasets/` directory), they are referred to as:\n",
    "\n",
    "- `customers`: `reviewerID`\n",
    "- `products`: `asin`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "G_amzn = load_amazon_reviews()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "NetworkX provides [`nx.bipartite.matrix.biadjacency_matrix()`](https://networkx.github.io/documentation/stable/reference/algorithms/generated/networkx.algorithms.bipartite.matrix.biadjacency_matrix.html#networkx.algorithms.bipartite.matrix.biadjacency_matrix) function that lets you get the biadjacency matrix of a graph object. This returns a `scipy.sparse` matrix. Sparse matrices are commonly used to represent graphs, especially large ones, as they take up much less memory."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Exercise\n",
    "\n",
    "Read the [docs](https://networkx.github.io/documentation/stable/reference/algorithms/generated/networkx.algorithms.bipartite.matrix.biadjacency_matrix.html#networkx.algorithms.bipartite.matrix.biadjacency_matrix) on how to use the `biadjacency_matrix()` function. \n",
    "\n",
    "You probably would want to first define a function that gets all nodes from a partition."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def get_partition_nodes(G, partition):\n",
    "    \"\"\"\n",
    "    A function that returns nodes from one partition.\n",
    "    \n",
    "    Assumes that the attribute key that stores the partition information\n",
    "    is 'bipartite'.\n",
    "    \"\"\"\n",
    "    # Put your code here.\n",
    "    return _________"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Exercise\n",
    "\n",
    "Now, use the `get_partition_nodes()` function to get the `row_order` and `column_order` nodes from the Amazon music review graph, then get the biadjacency matrix using `nx.bipartite.biadjacency_matrix`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "customer_nodes = get_partition_nodes(G_amzn, ________)\n",
    "mat = _________"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Exercise\n",
    "\n",
    "Let's find out which customers reviewed the most number of music items.\n",
    "\n",
    "To do so, you can break the problem into a few steps.\n",
    "\n",
    "First off, compute the customer projection using matrix operations."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "customer_mat = ________"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Next, get the diagonals of the customer-customer matrix. Recall here that in `customer_mat`, the diagonals correspond to the degree of the customer nodes in the bipartite matrix.\n",
    "\n",
    "**Hint:** SciPy sparse matrices provide a `.diagonal()` method that returns the diagonal elements."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Get the diagonal.\n",
    "degrees = ___________"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Finally, find the index of the customer that has the highest degree."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "cust_idx = ___________\n",
    "cust_idx"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "It should be customer 294 in the `customer_nodes` list.\n",
    "\n",
    "### Exercise\n",
    "\n",
    "Verify that this holds when looking at the degrees of each customer in `customer_nodes`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Compute the degree of each customer according to the order\n",
    "# in customer_nodes\n",
    "cust_degrees = ________________\n",
    "np.argmax(cust_degrees)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Exercise\n",
    "\n",
    "Let's now also compute which two customers are similar, based on shared reviews. To do so involves the following steps:\n",
    "\n",
    "1. We construct a sparse matrix consisting of only the diagonals. `scipy.sparse.diags(elements)` will construct a sparse diagonal matrix based on the elements inside `elements`.\n",
    "1. Subtract the diagonals from the customer matrix projection. This yields the customer-customer similarity matrix, which should only consist of the off-diagonal elements of the customer matrix projection.\n",
    "1. Finally, get the indices where the weight (shared number of between the customers is highest. (*This code is provided for you.*)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import scipy.sparse as sp"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Construct diagonal elements.\n",
    "customer_diags = __________\n",
    "# Subtract off-diagonals.\n",
    "off_diagonals = _________\n",
    "# Compute index of most similar individuals.\n",
    "np.unravel_index(np.argmax(off_diagonals), customer_mat.shape)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Performance: Object vs. Matrices\n",
    "\n",
    "Finally, to motivate why you might want to use matrices rather than graph objects to compute some of these statistics, let's time the two ways of getting to the same answer."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Objects"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from time import time\n",
    "\n",
    "start = time()\n",
    "G_cust = nx.bipartite.weighted_projected_graph(G_amzn, customer_nodes)\n",
    "most_similar_customers = sorted(G_cust.edges(data=True), key=lambda x: x[2]['weight'], reverse=True)[0]\n",
    "end = time()\n",
    "print(f'{end - start:.3f} seconds')\n",
    "print(f'Most similar customers: {most_similar_customers}')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Matrices"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "start = time()\n",
    "mat = nx.bipartite.matrix.biadjacency_matrix(G_amzn, customer_nodes)\n",
    "cust_mat = mat @ mat.T\n",
    "degrees = customer_mat.diagonal()\n",
    "customer_diags = sp.diags(degrees)\n",
    "off_diagonals = customer_mat - customer_diags\n",
    "c1, c2 = np.unravel_index(np.argmax(off_diagonals), customer_mat.shape)\n",
    "\n",
    "end = time()\n",
    "print(f'{end - start:.3f} seconds')\n",
    "print(f'Most similar customers: {customer_nodes[c1]}, {customer_nodes[c2]}, {cust_mat[c1, c2]}')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You may notice that it's much easier to read the \"objects\" code, but the matrix code way outperforms the object code. This then becomes a great reason to use matrices (even better, sparse matrices)!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "nams",
   "language": "python",
   "name": "nams"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
